package com.customization.api.e9sso.cmd;

import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.util.AuthManager;

import com.cloudstore.dev.api.util.Util_DataMap;
import com.cloudstore.eccom.common.WeaIndexManager;
import com.cloudstore.eccom.result.WeaResultMsg;
import com.customization.commons.Console;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;

import weaver.general.AES;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.rsa.security.Base64;
import weaver.rsa.security.IOUtils;

import weaver.rsa.security.RSA;


import javax.crypto.Cipher;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyFactory;

import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class SsoTokenCmd   extends AbstractCommonCommand<Map<String,Object>> {
    private String appid;
    private static ThreadLocal<Cipher> encryptThreadLocal = new ThreadLocal();
    public SsoTokenCmd(User user, Map<String,Object> params) {
        this.user = user;
        this.params = params;
        appid=Util.null2String(params.get("appid"));

    }


    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        Map<String, Object> apidatas = new HashMap<String, Object>();
        if("".equals(appid)){
            apidatas.put("status",false);
            apidatas.put("msg","appid不能为空或者没要找到对应的用户");
            return apidatas;
        }

        RecordSet rs= new RecordSet();



        String ip=Util.null2String(params.get("param_ip"));

        String allowip=Util.null2String(rs.getPropValue("WeaverLoginClient",appid));
        if(allowip.contains("*.*.*.*")){

        }else{
            if(!allowip.contains(ip)){
                apidatas.put("status",false);
                apidatas.put("msg","当前访问的IP:"+ip+"无访问权限！");
                return apidatas;

            }
        }



        /*
        if(!HrmUserVarify.checkUserRight("LogView:View", user)){
            apidatas.put("hasRight", false);
            return apidatas;
        }
        */
        try {
            String workcode=Util.null2String(params.get("workcode"));


            String userid="";

            rs.execute("select * from hrmresource where workcode='"+workcode +"'  and  （accounttype =0 or accounttype is null ） ");
            if(rs.next()){
                userid=rs.getString("id");
            }

            //如果查询不到员工编号，则按照登录名查询
            if(userid.equals("")){
                rs.execute("select * from hrmresource where loginid='"+workcode +"'  and  （accounttype =0 or accounttype is null ） ");
                if(rs.next()){
                    userid=rs.getString("id");
                }
            }


            if("".equals(userid)){
                apidatas.put("status",false);
                apidatas.put("msg","编号workcode不能为空或者没要找到对应的用户");
                return apidatas;
            }else {

                //注册信息
                JSONObject registInfo = regist();

                if (registInfo.getString("status").equals("true")) {
                    String secrit = registInfo.getString("secrit");
                    String spk = registInfo.getString("spk");


                    //获取token
                    JSONObject tokenInfo = applytoken(secrit, spk);

                    if(tokenInfo.getString("status").equals("true")){
                        String token = tokenInfo.getString("token");

                        userid = encrypt(userid, "utf-8", spk);
                        apidatas.put("status", true);
                        apidatas.put("apiToken", token);
                        apidatas.put("userId", userid);

                        apidatas.put("ssoToken", getSsoToken(appid,workcode,ip));
                        apidatas.put("createNodeID", getCreateNodeID(Util.null2String(params.get("requestId"))));

                        String dispatchWorkcode=Util.null2String(params.get("dispatchWorkcode"));


                        return apidatas;
                    }else{
                        apidatas.put("status",false);
                        apidatas.put("msg",tokenInfo.getString("msg"));
                        return apidatas;
                    }

                }else{

                    apidatas.put("status",false);
                    apidatas.put("msg",registInfo.getString("msg"));
                    return apidatas;
                }


            }



        } catch (Exception e) {
            e.printStackTrace();
        }
        return apidatas;
    }


    /**
     * 注册
     * @return
     */
    public JSONObject regist() {



        //获取当前异构系统RSA加密的公钥
        String cpk = new RSA().getRSA_PUB();
        //当前异构系统用于向ECOLOGY注册时使用的账号密码通过DES加密后密文进行传输




        //调用ECOLOGY系统接口进行注册
        String data = null;
        try {
            WeaResultMsg weaResultMsg = new WeaResultMsg(false);
            try {
                if (AuthManager.hasRegistData(appid)) {
                    String secrittemp = AuthManager.updateSecrit(appid, cpk);
                    weaResultMsg.put("errcode", "0");
                    weaResultMsg.put("secrit", secrittemp);
                    weaResultMsg.put("spk", RSA.getRSA_PUB());
                    weaResultMsg.put("errmsg", "ok");
                    Util_DataMap.setObjVal(appid, appid);
                    Util_DataMap.setObjVal(appid + "rsa", cpk);
                    data= weaResultMsg.success("ok").toString();
                } else {
                    weaResultMsg.put("errcode", "1");
                    weaResultMsg.put("errmsg", "注册失败没有在找到正确的APPID:" + appid);
                    data= weaResultMsg.fail("注册失败没有在找到正确的APPID:" + appid).toString();
                }
            } catch (Exception e) {
                e.printStackTrace();
                weaResultMsg.fail(e.getMessage());
                data= weaResultMsg.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回的数据格式为json，具体格式参数格式请参考文末API介绍。
        //注意此时如果注册成功会返回秘钥信息,请根据业务需要进行保存。
        JSONObject json=JSONObject.parseObject(data);

        return json;
    }



    /**
     *
     * @param secret 调用注册接口返回的secret参数值
     * @param spk 注册接口成功时返回的apk参数值
     * @throws Exception
     * @return
     */
    public JSONObject applytoken(String secret, String spk){


        //对秘钥进行加密传输，防止篡改数据
        secret = encrypt(secret, "utf-8", spk);

        //调用ECOLOGY系统接口进行申请
        String data = null;
        try {//算法参考com.cloudstore.dev.api.service.ServiceAuth.AuthToken方法


            WeaResultMsg weaResultMsg = new WeaResultMsg(false);
            try {
                RSA var6 = new RSA();
                secret = var6.decrypt((HttpServletRequest)null, secret, true);
                if (StringUtils.isBlank(secret)) {
                    weaResultMsg.fail("解密失败！").toString();
                }
                String var7 = AuthManager.getSPKey(appid, secret);
                if (StringUtils.isNotBlank(var7)) {
                    String var8 = WeaIndexManager.getGuid();
                    Util_DataMap.setValAuto(appid + var8, appid, 1800);
                    weaResultMsg.put("token", var8);
                    weaResultMsg.success("获取成功!");
                } else {
                    weaResultMsg.fail("认证信息错误！");
                }
            } catch (Exception var9) {
                var9.printStackTrace();
                weaResultMsg.fail(var9.getMessage());
            }

            data= weaResultMsg.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回的数据格式为json，具体格式参数格式请参考文末API介绍。
        //注意此时如果申请成功会返回token,请根据业务需要进行保存。
        System.out.println("applytoken:"+data);
        return JSONObject.parseObject(data);
        /**********************其它业务逻辑实现***********************/
    }


    public String encrypt(String value, String charset, String rsaPublicFile ) {
        String result = "";

        try {
            byte[] msgBytes = value.getBytes(charset);
            if (msgBytes.length <= 245) {
                PublicKey publicKey = null;

                publicKey = getFromBase64String(rsaPublicFile);


                Cipher cipher = (Cipher)encryptThreadLocal.get();
                if (cipher == null) {
                    cipher = Cipher.getInstance("RSA");
                    cipher.init(1, publicKey);
                    encryptThreadLocal.set(cipher);
                }

                byte[] results = cipher.doFinal(msgBytes);
                return weaver.rsa.security.Base64.encodeBase64String(results);
            }

        } catch (Exception var12) {
            var12.printStackTrace();

        }

        return result;

    }

    public static PublicKey getFromBase64String(String publicKeyString) throws Exception {
        InputStream is = new ByteArrayInputStream(publicKeyString.getBytes());
        return getFromBase64((InputStream)is);
    }

    public static PublicKey getFromBase64(InputStream input) throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        IOUtils.copy(input, os);
        byte[] keyBytes = os.toByteArray();
        byte[] ks = Base64.decodeBase64(keyBytes);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(ks);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }


    /**
     *
     * @param appid 应用ID
     * @param workcode  员工编号
     * @param ip  IP地址
     * @return
     */
    public String getSsoToken(String appid,String workcode,String ip) {
        try {
            String loginid = "";
            RecordSet rst = new RecordSet();
            if (!workcode.equals("")) {

                rst.execute("select * from hrmresource where workcode ='" + workcode + "'");
                if (rst.next()) {
                    loginid = rst.getString("loginid");
                }
            }

            if(loginid.equals("")){
                rst.execute("select * from hrmresource where loginid='"+workcode+"'");
                if(rst.next()){
                    loginid = rst.getString("loginid");
                }
            }


            String salt = "yjcust";

           // RecordSet var19 = new RecordSet();
            //var19.executeQuery("select * from weaver_sso where token_isuse='1'", new Object[0]);
            //if (!var19.next()) {
             //   return "appid:" + appid + " has not permission to use!!!";
            //}

            if (loginid == null || "".equals(loginid)) {
                Console.log(" has no  loginidTemp account: " + workcode + "!!!");
                return " has no  account: " + workcode;
            }

            String datatime = (new Date()).getTime() + "";
            String token = AES.encrypt(loginid + "|" + datatime + "|" + appid, salt);
            RecordSet var24 = new RecordSet();
            var24.executeQuery("select * from hrmresource where loginid=? ", new Object[]{loginid});

            if (var24.next()) {
                var24.execute("select max(id ) maxid from sso_login_oa ");
                var24.next();
                String maxid = var24.getString("maxid");
                if ("".equals(maxid)) {
                    maxid = "1";
                } else {
                    maxid = Integer.valueOf(maxid) + 1 + "";
                }
                var24.executeUpdate("insert into sso_login_oa values(?,?,?,'0',?,?,'','','' )", new Object[]{maxid, loginid, loginid, datatime, token});

                return token;
            } else {
                return "has no account: " + loginid + "!!!";
            }

        } catch (Exception e) {
            e.printStackTrace();
            Console.log(e.toString());
        }

        return "";
    }


     public String getCreateNodeID(String requestid){
        RecordSet rs= new RecordSet();
        if(requestid.equals("")){
            return "";
        }
        rs.execute("select nodeid from  workflow_nodebase,workflow_flownode,workflow_requestbase where workflow_flownode.nodeid=workflow_nodebase.id and nodetype=0 and workflow_requestbase.workflowid=workflow_flownode.workflowid and workflow_requestbase.requestid='"+requestid+"'");
        rs.first();

        return rs.getString("nodeid");
    }


}
